package socketinterface;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import jp.kentaro.plugin.memoryimageview.views.ViewPart;

import org.eclipse.swt.widgets.Display;

public class ControlServer implements Runnable {
	public  ViewPart     view;
	private int          serverPort = 20000;
	private ServerSocket serverSocket = null;
	private Logger       logger;
	
	ControlServer(ViewPart view) {
		this.view = view;
	}
	
	public void setPortNumber(int portNumber) {
		this.serverPort = portNumber;
	}
	
	public void startServer() {
		try {
			serverSocket = new ServerSocket(serverPort);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger = new ConsoleLogger();
		
		new Thread(this).start();
	}
	
	public void run() {
		// TODO Auto-generated method stub
		Socket clientSocket = null;
		for(;;) {
			try {
				clientSocket = serverSocket.accept();
				EchoProtocol protocol = new EchoProtocol(clientSocket, logger);
				Thread thread = new Thread(protocol);
				thread.start();
				logger.writeEntry("Create and started Thread = " + thread.getName());
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.writeEntry("Exception = " + e.getMessage());
			}
		}
	}
}
